package org.example.fastproject.web.sys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.fastproject.core.bean.PageParam;
import org.example.fastproject.core.bean.ViewResult;
import org.example.fastproject.web.sys.model.SysRole;
import org.example.fastproject.web.sys.model.dto.role.RoleInsertDto;
import org.example.fastproject.web.sys.model.dto.role.RolePermissionDto;
import org.example.fastproject.web.sys.model.dto.role.RoleUpdateDto;
import org.example.fastproject.web.sys.model.vo.role.RoleVo;
import org.example.fastproject.web.sys.service.SysRoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author 王海舟
 * @since 2023-01-16 11:48:46
 */
@RestController
@RequestMapping("/sys/sysRole")
@Api(tags = "系统：角色管理")
public class SysRoleController {
    @Resource
    private SysRoleService roleService;

    @PostMapping("/save")
    @ApiOperation("新增角色")
    @PreAuthorize("hasAuthority('role.save')")
    public ViewResult<Long> save(@RequestBody RoleInsertDto dto){
        boolean success = roleService.save(dto);
        if(success)
            return ViewResult.success("角色保存成功");
        return ViewResult.error("角色保存失败");
    }

    @DeleteMapping("/remove")
    @ApiOperation("删除角色")
    @PreAuthorize("hasAuthority('role.remove')")
    public ViewResult remove(@RequestParam Long id){
        boolean success = roleService.remove(id);
        if(success)
            return ViewResult.success("角色删除成功");
        return ViewResult.error("角色删除失败");
    }

    @PostMapping("/update")
    @ApiOperation("更新角色信息")
    @PreAuthorize("hasAuthority('role.update')")
    public ViewResult update(@RequestBody RoleUpdateDto dto){
        boolean success = roleService.update(dto);
        if(success)
            return ViewResult.success("角色更新成功");
        return ViewResult.error("角色更新失败");
    }

    @PostMapping("/page")
    @ApiOperation("分页查询角色信息列表")
    @PreAuthorize("hasAuthority('role.page')")
    public ViewResult<Page<RoleVo>> page(@RequestBody PageParam param){
        Page<RoleVo> page = roleService.page(param);
        return ViewResult.success(page);
    }

    @GetMapping("/{id}")
    @ApiOperation("通过角色id获取角色信息")
    @PreAuthorize("hasAuthority('role.id')")
    public ViewResult<SysRole> getById(@PathVariable Long id){
        SysRole sysRole = roleService.getById(id);
        return ViewResult.success(sysRole);
    }

    @PostMapping("/permission")
    @ApiOperation("给角色分配权限")
    @PreAuthorize("hasAuthority('role.permission')")
    public ViewResult permission(@RequestBody RolePermissionDto dto){
        boolean success = roleService.permission(dto);
        if(success)
            return ViewResult.success("角色权限分配成功");
        return ViewResult.error("角色权限分配失败");
    }

}
